
package com.wulian.user.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.wulian.common.entity.SysUser;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wulian.common.constants.CommonConstants;
import com.wulian.common.controller.BaseController;
import com.wulian.common.dto.UserDto;
import com.wulian.common.dto.UserInfo;
import com.wulian.common.util.Query;
import com.wulian.common.util.Result;
import com.wulian.common.vo.ResultMoudel;
import com.wulian.user.dto.RoleDTO;
import com.wulian.user.entity.SysRole;
import com.wulian.user.entity.SysRoleDept;
import com.wulian.user.mapper.SysDeptMapper;
import com.wulian.user.mapper.SysRoleDeptMapper;
import com.wulian.user.mapper.SysRoleMapper;
import com.wulian.user.service.SysRoleMenuService;
import com.wulian.user.service.SysRoleService;

/**
 * @author Administrator
 * @date 2017/11/5
 */
@RestController
@RequestMapping("/role")
public class RoleController extends BaseController<UserDto> {
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysRoleDeptMapper sysRoleDeptMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    
    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 通过ID查询角色信息
     *
     * @param id ID
     * @return 角色信息
     */
    @GetMapping("/{id}")
    public SysRole role(@PathVariable Integer id) {
    	SysRole sysRole = sysRoleService.selectById(id);
    	if(null == sysRole){
    		return sysRole;
    	}
    	Map<String,Object> paramMap = new HashMap<String,Object>();
    	paramMap.put("role_id", sysRole.getRoleId());
    	List<SysRoleDept> sysRoleDeptList = sysRoleDeptMapper.selectByMap(paramMap);
    	if(null != sysRoleDeptList && sysRoleDeptList.size() > 0){
    		Integer deptId = sysRoleDeptList.get(0).getDeptId();
    		sysRole.setRoleDeptId(deptId);
    		String name = sysDeptMapper.selectById(deptId).getName();
    		sysRole.setDeptName(name);
    	}
        return sysRole;
    }

    /**
     * 添加角色
     *
     * @param roleDto 角色信息
     * @return success、false
     */
    @PostMapping
    public Result<Boolean> role(@RequestBody RoleDTO roleDto) {
    	//默认角色为未删除标识
    	roleDto.setDelFlag(CommonConstants.DEL_FLAG_NO);
		SysUser sysUser = getCurrentUser().getSysUser();
		if(null == sysUser.getCompanyId()){
			return new Result(false);
		}
		roleDto.setRoleDeptId(sysUser.getDeptId());
		roleDto.setCompanyId(sysUser.getCompanyId());
		return new Result<>(sysRoleService.insertRole(roleDto));
    }
    
    @PostMapping("/checkIsExist")
    public ResultMoudel checkIsExist(String roleCode,Integer id){
    	if(StringUtils.isBlank(roleCode)){
    		return new ResultMoudel(ResultMoudel.ERROR_FLAG,"参数不全");
    	}
    	HashMap<String,Object> hashMap = new HashMap<String,Object>();
    	hashMap.put("role_code", roleCode);
    	List<SysRole> sysRoleList = sysRoleMapper.selectByMap(hashMap);
    	if(null != sysRoleList && sysRoleList.size() > 0){
    		if(null == id){
    			return new ResultMoudel(ResultMoudel.ERROR_FLAG,"角色标识已存在");
    		}else{
    			//原始数据
    			SysRole sysRole = sysRoleMapper.selectById(id);
    			if(null != sysRole){
    				if(sysRole.getRoleCode().equals(sysRoleList.get(0).getRoleCode())){
    					//正常通过
    				}else{
    					return new ResultMoudel(ResultMoudel.ERROR_FLAG,"角色标识已存在");
    				}
    			}else{
    				return new ResultMoudel(ResultMoudel.ERROR_FLAG,"参数错误");
    			}
    		}
    	}
    	return new ResultMoudel(ResultMoudel.SUCCESS_FLAG,"角色标识验证通过");
    }

    /**
     * 修改角色
     *
     * @param roleDto 角色信息
     * @return success/false
     */
    @PutMapping
    public Result<Boolean> roleUpdate(@RequestBody RoleDTO roleDto) {
        return new Result<>(sysRoleService.updateRoleById(roleDto));
    }

    @DeleteMapping("/{id}")
    public ResultMoudel roleDel(@PathVariable Integer id) {
        SysRole sysRole = sysRoleService.selectById(id);
        sysRole.setDelFlag(CommonConstants.STATUS_DEL);
        ResultMoudel ret = sysRoleService.delRoleById(sysRole);
        return ret;
    }

    /**
     * 获取角色列表
     *
     * @param
     * @return 角色列表
     */
    @GetMapping("/roleList")
    public List<SysRole> roleList() {
        return sysRoleService.selectListByDeptId();

    }

    /**
     * 分页查询角色信息
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @RequestMapping("/rolePage")
    public Page rolePage(@RequestParam Map<String, Object> params) {
    	Integer deptId = null;
    	if(null != params && params.size() > 0){
    		Object dept_id = params.get("deptId");
    		if(null != dept_id){
    			deptId = Integer.valueOf((String)params.get("deptId"));
    		}
    	}
    	UserInfo user = getCurrentUser();
    	//获取当前用户所属部门ID
    	deptId = null == deptId ? user.getSysUser().getDeptId() : deptId;
        params.put(CommonConstants.DEL_FLAG, CommonConstants.STATUS_NORMAL);
        params.put("dept_id", deptId);
        return sysRoleService.selectwithDeptPage(new Query<>(params), new EntityWrapper<>());
    }

    /**
     * 更新角色菜单
     *
     * @param roleId  角色ID
     * @param menuIds 菜单结合
     * @return success、false
     */
    @PutMapping("/roleMenuUpd")
    public Result<Boolean> roleMenuUpd(Integer roleId, @RequestParam("menuIds") String menuIds) {
    	Integer[] menuIdArr = null;
    	if(StringUtils.isNotBlank(menuIds)){
    		String[] menuIdArray = menuIds.split(",");
    		//将String数组转成Integer数组
    		menuIdArr = Arrays.stream(menuIdArray).map(Integer::valueOf).toArray(Integer[]::new);
    	}
        SysRole sysRole = sysRoleService.selectById(roleId);
        return new Result<>(sysRoleMenuService.insertRoleMenus(sysRole.getRoleCode(), roleId, menuIdArr));
    }
    
    /**
     * 
    * @Title: roleListByDeptId
    * @Description:(过滤部门下的角色)
    * @param @param deptId
    * @param @return    参数
    * @return ResultMoudel    返回类型
    * @author mzh
    * @date 2020年4月13日
    * @version V1.0
    * @throws
     */
    @PostMapping("/roleListByDeptId")
	public ResultMoudel roleListByDeptId(@RequestParam("deptId") String deptId) {
    	UserInfo currentUser = getCurrentUser();
    	String dept_id = StringUtils.isBlank(deptId) ? String.valueOf(currentUser.getSysUser().getDeptId()) : deptId;
    	// 所有的角色信息
		List<SysRole> selectSysRoleList = sysRoleService.selectListByDeptId();
		// 所有的角色与部门的关系数据
		List<SysRoleDept> sysRoleDeptList = sysRoleDeptMapper.selectByMap(null);
		List<String> roleList = sysRoleDeptList.stream()
				.filter(srd -> null != srd.getDeptId() && dept_id.equals(String.valueOf(srd.getDeptId())))
				.map(srd -> String.valueOf(srd.getRoleId())).collect(Collectors.toList());
		selectSysRoleList = selectSysRoleList.stream().filter(sr -> roleList.contains(String.valueOf(sr.getRoleId())))
				.collect(Collectors.toList());
		return new ResultMoudel("success", selectSysRoleList);
	}
	@ApiOperation(httpMethod = "GET",value = "查询公司下的角色信息")
	@GetMapping("/getRoleByCompanyId")
	public ResultMoudel getRoleByCompanyId(SysRole sysRole){
		ResultMoudel resultMoudel = new ResultMoudel();
		Integer companyId = getCurrentUser().getSysUser().getCompanyId();
		if(null == companyId){
			return resultMoudel;
		}
		sysRole.setCompanyId(companyId);
		List<SysRole> roleByCompanyId = sysRoleService.getRoleByCompanyId(sysRole);
		return resultMoudel.success(roleByCompanyId);
	}
}
